<script setup lang="ts">
/* eslint-disable no-console */
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { CalplanApi, DictApi } from '#/api';

import { reactive, ref, watchEffect } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VxeButton } from '@vben/plugins/vxe-table';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  addPlanteam,
  deletePlanteam,
  deleteShift,
  DictResp,
  getPlanteamList,
  getShiftList,
  getTeammemberById,
} from '#/api';
import { getToolBarBtns, setToolBarBtnDefaultDisabled } from '#/utils';

import {
  confirm,
  messageError,
  messageSuccess,
} from '../../../wm/common/common';
import editShift from './edit-shift.vue';
import searchTeam from './search-Team.vue';

const props = defineProps(['plan', 'calendar']);
const planId = props.plan;
const calendarType = props.calendar;
const ids = ref('');

watchEffect(() => {});
const mes_index_type = reactive<DictApi.SelectOption[]>([]);
DictResp(['mes_index_type']).then((res) => {
  console.log(res);

  // 将两个数组合并
  if (res.mes_index_type) {
    mes_index_type.push(...res.mes_index_type);
  }
});
// 存储选中行的响应式变量
const selectedRows = ref<CalplanApi.Row1[]>([]);

const [Shift, editmodalApi1] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: editShift,
  destroyOnClose: true,
});

// 表格左上角按钮
const buttons = getToolBarBtns();
const gridEvents1: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    console.log(code);
    switch (code) {
      case 'myAdd': {
        // console.log(planId.value);

        // 新增逻辑
        console.log('新增');
        editmodalApi1
          .setData({ planId })
          .setState({
            title: '添加班次',
          })
          .open();
        break;
      }
      case 'myDel': {
        // 删除逻辑
        // console.log('删除');
        deleteCalshift(selectedRows.value as any);
        break;
      }
      case 'myEdit': {
        // 修改逻辑
        alterCalshift(selectedRows.value[0] as any);
        console.log('修改');
        break;
      }
      default: {
        break;
      }
    }
  },
  checkboxChange({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
  checkboxAll({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
};

const gridEvents2: VxeGridListeners = {
  checkboxChange({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
  checkboxAll({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
};
const gridEvents3: VxeGridListeners = {
  checkboxChange({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
  checkboxAll({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
};

const gridOptions1 = reactive<VxeGridProps<CalplanApi.Row1>>({
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    {
      align: 'left',
      field: 'shiftId',
      title: '',
      type: 'checkbox',
      width: 50,
    },
    { field: 'orderNum', title: '序号' },
    { field: 'shiftName', title: '班次名称' },
    { field: 'startTime', title: '开始时间' },
    { field: 'endTime', title: '结束时间' },
    { field: 'standerVal', title: '备注' },
    { slots: { default: 'action' }, fixed: 'right', title: '操作' },
  ],
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const res = await getShiftList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          planId: planId as any,
        });
        return {
          total: res.total,
          items: res.rows,
        };
      },
    },
  },

  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    refresh: true,
    buttons: buttons.value,
  },
});

const gridOptions2 = reactive<VxeGridProps<CalplanApi.Row>>({
  columns: [
    { field: 'teamCode', title: '班组编号' },
    { field: 'teamName', title: '班组名称' },
    { slots: { default: 'action' }, fixed: 'right', title: '操作' },
  ],
  keepSource: true,
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const res = await getPlanteamList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          planId: planId as any,
          calendarType: calendarType as any,
        });
        ids.value = res.rows.map((item) => item.teamId).join(',');
        await getTeammemberById({
          ids: ids.value,
        }).then((res) => {
          grid3Api.setGridOptions({ data: res.data });
        });
        return {
          total: res.total,
          items: res.rows,
        };
      },
    },
  },
});
const gridOptions3 = reactive<VxeGridProps<CalplanApi.Row>>({
  columns: [
    { field: 'userName', title: '用户名' },
    { field: 'nickName', title: '用户昵称' },
    { field: 'tel', title: '电话' },
  ],
  keepSource: true,
  pagerConfig: {
    enabled: false,
  },
});

function alterCalshift(row: CalplanApi.Row1) {
  // console.log(row);
  editmodalApi1
    .setState({
      title: '修改班次',
    })
    .setData({ row })
    .open();
}

function deleteCalshift(row: CalplanApi.Row1) {
  console.log(row);
  const ids = Array.isArray(row)
    ? row.map((item) => item.shiftId)
    : [row.shiftId];
  const idString = ids.join(',');
  confirm(`是否确认删除班次？`, '提示').then(() => {
    deleteShift(idString)
      .then(() => {
        refreshGrid(`删除成功`);
      })
      .catch((error) => {
        messageError(error);
      });
  });
}
function delPlanteam(row: CalplanApi.Row2) {
  console.log(row);
  const ids = Array.isArray(row)
    ? row.map((item) => item.recordId)
    : [row.recordId];
  const idString = ids.join(',');
  confirm(`是否确认删除班组`, '提示').then(() => {
    deletePlanteam(idString)
      .then(() => {
        refreshGrid(`删除成功`);
      })
      .catch((error) => {
        messageError(error);
      });
  });
}

// 获取弹框中检测项表格
const [Grid1, grid1Api] = useVbenVxeGrid({
  gridOptions: gridOptions1,
  gridEvents: gridEvents1,
});

// 获取弹框中物料产品表格
const [Grid2, grid2Api] = useVbenVxeGrid({
  gridOptions: gridOptions2,
  gridEvents: gridEvents2,
});
const [Grid3, grid3Api] = useVbenVxeGrid({
  gridOptions: gridOptions3,
  gridEvents: gridEvents3,
});

const [searchModal, searchModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: searchTeam,
  destroyOnClose: true,
  async onClosed() {
    const planteamValue: CalplanApi.CalplanListParams4 =
      {} as CalplanApi.CalplanListParams4;
    const data = searchModalApi.getData();
    console.log(searchModalApi.getData());
    planteamValue.planId = planId;
    planteamValue.teamId = data.teamId;
    planteamValue.calendarType = calendarType;
    planteamValue.teamCode = data.teamCode;
    planteamValue.teamName = data.teamName;
    console.log(planteamValue);
    try {
      await addPlanteam(planteamValue!);
      // emit('success', '新增成功');
      refreshGrid('新增成功');
      searchModalApi.close();
    } finally {
      searchModalApi.lock(false);
    }
    // baseFormApi.setFieldValue('qcTool', searchModalApi.getData().qcTool);
    // baseFormApi.setFieldValue('indexName', searchModalApi.getData().indexName);
    // baseFormApi.setFieldValue('indexId', searchModalApi.getData().indexId);
    // baseFormApi.setFieldValue('indexType', searchModalApi.getData().indexType);
    // baseFormApi.setFieldValue('indexCode', searchModalApi.getData().indexCode);
  },
});

function choiceTeam() {
  searchModalApi.open();
}

function refreshGrid(msg: string) {
  messageSuccess(msg);
  grid1Api.query();
  grid2Api.query();
  // grid3Api.query();
}
</script>

<template>
  <div>
    <Shift @success="refreshGrid" />
    <searchModal @success="refreshGrid" />
    <el-tabs type="border-card">
      <el-tab-pane label="班次">
        <Grid1>
          <template #action="{ row }">
            <VxeButton
              mode="text"
              icon="vxe-icon-signature"
              @click="alterCalshift(row)"
              status="primary"
            >
              修改
            </VxeButton>
            <VxeButton
              icon="vxe-icon-delete"
              mode="text"
              @click="deleteCalshift(row)"
              status="error"
            >
              删除
            </VxeButton>
          </template>
        </Grid1>
      </el-tab-pane>
      <el-tab-pane class="flex w-full" label="班组">
        <el-card class="w-1/2">
          <template #header>
            <div class="flex items-center justify-between">
              <span>班组</span>
              <el-button @click="choiceTeam" text type="primary">
                添加
              </el-button>
            </div>
          </template>
          <Grid2>
            <template #action="{ row }">
              <VxeButton
                icon="vxe-icon-delete"
                mode="text"
                @click="delPlanteam(row)"
                status="error"
              >
                删除
              </VxeButton>
            </template>
          </Grid2>
        </el-card>
        <el-card class="w-1/2">
          <template #header>
            <div>
              <span>成员</span>
            </div>
          </template>
          <Grid3 />
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
